package com.clippick.setting;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import co.kr.clippick.R;

import com.clippick.LoginActivity;
import com.clippick.MainActivity;
import com.clippick.WalkThroughActivity;
import com.clippick.api.ClipPickListener;
import com.clippick.api.GetApi;
import com.clippick.clipboard.PollingService;
import com.clippick.clipboard.ShorcutNotificationService;
import com.clippick.common.GlobalValue;

public class SettingFragment extends Fragment implements
		OnCheckedChangeListener {
	// common
	private Context mContext;
	private MainActivity parent;
	private View view;

	// data:info
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	private boolean showNotifValue;

	// view
	private ImageView historyBottom, starBottom, settingBottom;

	// view
	private TextView userIdText, shortcutText;
	private Button tellButton, useButton, feedBackButton, logoutButton;
	private Button shortcutButton;
	private CheckBox autoSyncCheckBox, launchCheckBox,
			showNotificationCheckBox;
	private LinearLayout shortcutLinear;

	// id
	private static final String FLAG_INVITE = "invite";

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = (Context) getActivity();
		parent = (MainActivity) mContext;
		view = inflater.inflate(R.layout.setting, container, false);

		// preferences
		pref = mContext.getSharedPreferences(GlobalValue.KEY,
				Context.MODE_PRIVATE);
		editor = mContext.getSharedPreferences(GlobalValue.KEY,
				Context.MODE_PRIVATE).edit();

		// find view: layer
		settingBottom = (ImageView) view.findViewById(R.id.setting_bottom);
		historyBottom = (ImageView) view.findViewById(R.id.history_bottom);
		starBottom = (ImageView) view.findViewById(R.id.star_bottom);

		// set button layer
		settingBottom.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.btn_setting_bottom));
		historyBottom.setVisibility(View.INVISIBLE);
		starBottom.setVisibility(View.INVISIBLE);
		settingBottom.setVisibility(View.VISIBLE);

		// find view: setting
		shortcutButton = (Button) view.findViewById(R.id.notif_button);
		shortcutLinear = (LinearLayout) view.findViewById(R.id.notif_layer);
		userIdText = (TextView) view.findViewById(R.id.user_id);
		autoSyncCheckBox = (CheckBox) view.findViewById(R.id.auto_check);
		launchCheckBox = (CheckBox) view.findViewById(R.id.launch_check);
		// showNotificationCheckBox = (CheckBox)
		// view.findViewById(R.id.show_notif);
		tellButton = (Button) view.findViewById(R.id.tell_button);
		useButton = (Button) view.findViewById(R.id.how_button);
		feedBackButton = (Button) view.findViewById(R.id.feedback_button);
		logoutButton = (Button) view.findViewById(R.id.logout_button);
		logoutButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// logout animation
				scaleUpFadeOutAnimation(userIdText);
				handler.sendEmptyMessageDelayed(0, 500);
			}
		});

		// set action: feedback
		feedBackButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// start Feedback
				Intent intent = new Intent(mContext, FeedbackActivity.class);
				startActivity(intent);
			}
		});

		tellButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// first parameter must be written as FLAG_TASK
				new HttpTask().execute(FLAG_INVITE);
			}
		});

		useButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, WalkThroughActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.bottom_to_top,
						R.anim.top_to_bottom);
			}
		});

		shortcutLinear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editor = mContext.getSharedPreferences(GlobalValue.KEY,
						Context.MODE_PRIVATE).edit();
				if (showNotifValue) {
					editor.putBoolean("showNotif", false).commit();
					showNotifValue = false;
					showNotification(false);
					changeButtonDrawable(R.id.notif_button, true);
				} else {
					editor.putBoolean("showNotif", true).commit();
					showNotifValue = true;
					showNotification(true);
					changeButtonDrawable(R.id.notif_button, false);
				}

				Log.i("notif", pref.getBoolean("showNotif", false) + "");
			}
		});

		// set view: setting
		userIdText.setText(GlobalValue.USER_ID);

		// set checkbox action
		// showNotificationCheckBox.setOnCheckedChangeListener(this);
		autoSyncCheckBox.setOnCheckedChangeListener(this);
		launchCheckBox.setOnCheckedChangeListener(this);

		autoSyncCheckBox.setChecked(pref.getBoolean("autoSync", false));

		launchCheckBox.setChecked(GlobalValue.isAutoReboot(mContext));

		// showNotificationCheckBox.setChecked(GlobalValue.isShowNotification(mContext));

		showNotifValue = pref.getBoolean("showNotif", false);

		if (showNotifValue) {
			changeButtonDrawable(R.id.notif_button, false);
		} else {
			changeButtonDrawable(R.id.notif_button, true);
		}

		return view;
	}

	private void startLogout() {
		// disconnect with socketIO
		try {
			ClipPickListener.client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// delete user info
		editor.clear();

		// to hide walk through since the user must be our current user
		editor.putBoolean("walk", true);
		editor.commit();

		// stop service
		Intent intent = new Intent(mContext, PollingService.class);
		parent.stopService(intent);

		Intent notiIntent = new Intent(mContext, ShorcutNotificationService.class);
		parent.stopService(notiIntent);

		// start LoginActivity
		intent = new Intent(mContext, LoginActivity.class);
		startActivity(intent);
		parent.finish();
	}

	// button handler: timer
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			int start = msg.what;
			switch (start) {
			case 0:
				startLogout();
				break;

			case 1:

				break;
			}
		}
	};

	private void changeButtonDrawable(int layout, boolean value) {
		switch (layout) {
		case R.id.notif_button:
			if (value) {
				shortcutButton.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.btn_pref_check_a));
			} else {
				shortcutButton.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.btn_pref_check_n));
			}
			break;
		}
	}

	private void scaleUpFadeOutAnimation(View v) {
		Animation animation = AnimationUtils.loadAnimation(mContext,
				R.anim.scale_to_translate);
		v.startAnimation(animation);
	}

	private void autoSyncCheck(boolean isChecked) {
		Intent intent = new Intent(mContext, PollingService.class);
		if (isChecked) {
			parent.startService(intent);
		} else {
			parent.stopService(intent);
		}
	}

	private void launchCheck(boolean isChecked) {
		if (isChecked) {

		} else {

		}
	}

	private void showNotification(boolean isChecked) {
		Intent intent = new Intent(mContext, ShorcutNotificationService.class);
		
		Log.i("setting", "PollingService is " + isChecked);
		
		if (isChecked) {
			parent.startService(intent);
		} else {
			parent.stopService(intent);
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton button, boolean isChecked) {
		int id = button.getId();
		switch (id) {
		case R.id.auto_check:
			autoSyncCheck(isChecked);
			editor.putBoolean("autoSync", isChecked);
			editor.commit();
			break;

		case R.id.launch_check:
			launchCheck(isChecked);
			editor.putBoolean("autoLaunch", isChecked);
			editor.commit();
			break;

		// case R.id.show_notif:
		// editor.putBoolean("showNotif", isChecked);
		// editor.commit();
		// showNotification(isChecked);
		// break;
		}
	}

	// invite friend using generated url
	private void sendFriendUrl(String tinyUrl) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_SEND);
		intent.putExtra(Intent.EXTRA_TEXT,
				"you can copy paste anywhere like post-it!\n" + tinyUrl);
		intent.setType("text/plain");
		startActivity(Intent.createChooser(intent, "send to"));
	}

	public class HttpTask extends AsyncTask<String, String, String> {
		private ProgressDialog mProgress;
		private String result = "";
		private String task;

		protected void onPreExecute() {
			mProgress = new ProgressDialog(mContext);
			mProgress.setMessage("Loading");
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			task = params[0];
			if (task.equals(FLAG_INVITE)) {
				result = api.inviteTinyUrlApi();
			}

			return null;
		}

		protected void onPostExecute(String unused) {
			mProgress.dismiss();
			if (!result.equals("")) {
				if (task.equals(FLAG_INVITE)) {
					sendFriendUrl(result);
				}
			}
		}
	}
}
